package com.shivandragon.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.shivandragon.utils.MongoSingletonHolder;

public class PresentationViewController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private MongoSingletonHolder mongoSingletonHolder = MongoSingletonHolder.getInstance();
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if("1".equals(request.getParameter("wait"))) {
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String id = request.getParameter("_id");
		int retryCount = 3;
		DBObject presentationData = null;
		while(retryCount>0) {
			presentationData = mongoSingletonHolder.getPresentationsDBCollection().findOne(new BasicDBObject("_id", new ObjectId(id)));
			retryCount--;
			if(presentationData!=null) {
				break;
			} else {
				try {
					Thread.sleep(1500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	
		request.setAttribute("title", presentationData.get("title"));
		for(int i = 0; i < PrezConstants.MAX_IMAGES_PER_PREZ; i++) {
			if(presentationData.get("img"+i)!=null && !presentationData.get("img"+i).equals("")) {
				request.setAttribute("img"+i, "/img?_id="+id+"&slideIndex="+i);
				request.setAttribute("imgWidth"+i, presentationData.get("imgWidth"+i));
				request.setAttribute("imgHeight"+i, presentationData.get("imgHeight"+i));
				request.setAttribute("imgDesc"+i, presentationData.get("imgDesc"+i));
			}
		}
		
		request.getRequestDispatcher("/WEB-INF/presentationView.jsp").forward(request, response);
	}

}
